// 背包图标映射表（名称 -> 图标 URL 或 emoji）
// 注意：如果网络图标加载失败，会自动回退到 emoji
const ITEM_ICONS = {
    '武器': {
        emoji: '⚔️',
        url: 'https://raw.githubusercontent.com/twitter/twemoji/master/assets/svg/2694.svg'
    },
    '衣服': {
        emoji: '👕',
        url: 'https://raw.githubusercontent.com/twitter/twemoji/master/assets/svg/1f455.svg'
    },
    '裤子': {
        emoji: '👖',
        url: 'https://raw.githubusercontent.com/twitter/twemoji/master/assets/svg/1f456.svg'
    },
    '鞋子': {
        emoji: '👢',
        url: 'https://raw.githubusercontent.com/twitter/twemoji/master/assets/svg/1f462.svg'
    },
    '药水': {
        emoji: '🧪',
        url: 'https://raw.githubusercontent.com/twitter/twemoji/master/assets/svg/1f9ea.svg'
    }
};

// 背包控制器
class BackpackController {
    constructor() {
        this.items = [];
        this.tooltipEl = null;
        this.boundOutsideHandler = null;
        this.init();
    }

    init() {
        // 绑定关闭按钮
        document.getElementById('closeBackpack')?.addEventListener('click', () => {
            this.close();
        });

        // ESC 键关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.close();
            }
        });

        // 接收数据并显示
        this.loadData();

        console.log('背包界面已加载');
    }

    /**
     * 加载数据（从多种来源）
     */
    loadData() {
        let data = null;

        // 方法1: 从 localStorage 读取
        const dataStr = localStorage.getItem('testData');
        const timestamp = localStorage.getItem('testDataTimestamp');
        
        if (dataStr && timestamp) {
            const timeDiff = Date.now() - parseInt(timestamp);
            if (timeDiff < 5 * 60 * 1000) { // 5分钟内有效
                try {
                    data = JSON.parse(dataStr);
                } catch (error) {
                    console.error('解析localStorage数据失败:', error);
                }
            }
        }

        // 方法2: 从 URL 参数读取
        if (!data) {
            const urlParams = new URLSearchParams(window.location.search);
            const urlData = urlParams.get('testData');
            if (urlData) {
                try {
                    data = JSON.parse(urlData);
                } catch (error) {
                    console.error('解析URL参数失败:', error);
                }
            }
        }

        // 方法3: 从全局变量读取（如果是从主页面打开）
        if (!data && window.backpackData) {
            data = window.backpackData;
        }

        // 如果没有数据，使用默认测试数据（带稀有度）
        if (!data || !data.items || data.items.length === 0) {
            data = {
                items: [
                    { name: '武器', icon: null, count: 1, rarity: '金色', desc: '传说武器', itemLevel: 300, armor: 120, strength: 80, agility: 40, intelligence: 10, bindType: '拾取后绑定', equipSlots: ['头部','胸部','腿部'] },
                    { name: '衣服', icon: null, count: 2, rarity: '金色', desc: '传说护甲', itemLevel: 280, armor: 160, strength: 20, agility: 30, intelligence: 50, bindType: '自由装备', equipSlots: ['胸部'] },
                    { name: '裤子', icon: null, count: 3, rarity: '紫色', desc: '史诗护腿', itemLevel: 240, armor: 110, strength: 35, agility: 45, intelligence: 15, bindType: '拾取后绑定', equipSlots: ['腿部'] },
                    { name: '鞋子', icon: null, count: 4, rarity: '绿色', desc: '精良战靴', itemLevel: 180, armor: 70, strength: 10, agility: 25, intelligence: 5, bindType: '自由装备', equipSlots: ['脚部'] },
                    { name: '药水', icon: null, count: 5, rarity: '白色', desc: '基础回复品', itemLevel: 20, armor: 0, strength: 0, agility: 0, intelligence: 0, bindType: '自由装备', equipSlots: [] }
                ]
            };
        }

        this.items = data.items || [];
        this.render();
    }

    /**
     * 渲染背包物品列表
     */
    render() {
        const grid = document.getElementById('backpackGrid');
        if (!grid) return;

        grid.innerHTML = '';

        // 渲染物品
        this.items.forEach((item, index) => {
            const slot = this.createItemSlot(item, index);
            grid.appendChild(slot);
        });

        // 如果没有物品，显示空状态
        if (this.items.length === 0) {
            const emptySlot = document.createElement('div');
            emptySlot.className = 'item-slot empty';
            emptySlot.textContent = '空';
            grid.appendChild(emptySlot);
        }
    }

    /**
     * 创建物品槽位
     * @param {object} item 物品数据 {name, icon, count}
     * @param {number} index 索引
     * @returns {HTMLElement}
     */
    createItemSlot(item, index) {
        const slot = document.createElement('div');
        slot.className = 'item-slot ' + this.getRarityClass(item.rarity);
        slot.dataset.index = index;

        // 获取图标
        const iconHtml = this.getItemIcon(item);

        // 创建槽位内容
        slot.innerHTML = `
            <div class="item-icon">${iconHtml}</div>
            <div class="item-name">${this.escapeHtml(item.name || '未知物品')}</div>
            <div class="item-count">${item.count || 0}</div>
        `;

        // 点击事件（可选）
        slot.addEventListener('click', () => {
            console.log('点击物品:', item);
            this.showTooltip(item, slot);
        });

        // 悬停显示（桌面端）
        slot.addEventListener('mouseenter', () => {
            this.showTooltip(item, slot);
        });
        slot.addEventListener('mouseleave', () => {
            this.hideTooltip();
        });

        return slot;
    }

    /**
     * 稀有度转换为class
     * @param {string} rarity 中文稀有度（白色/绿色/紫色/金色）
     * @returns {string} rarity class
     */
    getRarityClass(rarity) {
        const map = {
            '白色': 'rarity-white',
            '绿色': 'rarity-green',
            '紫色': 'rarity-purple',
            '金色': 'rarity-gold'
        };
        return map[rarity] || 'rarity-white';
    }

    /**
     * 获取物品图标 HTML
     * @param {object} item 物品数据
     * @returns {string}
     */
    getItemIcon(item) {
        const itemName = item.name || '';
        const defaultIcon = this.getDefaultIcon(itemName);
        
        // 如果物品有自定义图标URL
        if (item.icon) {
            // 使用自定义图标，失败时回退到默认图标
            const escapedIcon = this.escapeHtml(item.icon);
            const escapedName = this.escapeHtml(item.name || '');
            return `<img src="${escapedIcon}" alt="${escapedName}" onerror="this.parentElement.innerHTML='${defaultIcon}';" />`;
        }

        // 如果映射表中有URL，尝试使用
        if (ITEM_ICONS[itemName] && ITEM_ICONS[itemName].url) {
            const escapedName = this.escapeHtml(itemName);
            const escapedUrl = this.escapeHtml(ITEM_ICONS[itemName].url);
            return `<img src="${escapedUrl}" alt="${escapedName}" onerror="this.parentElement.innerHTML='${defaultIcon}';" />`;
        }

        // 直接使用默认图标（emoji）
        return defaultIcon;
    }

    /**
     * 获取默认图标（emoji 或映射表）
     * @param {string} name 物品名称
     * @returns {string}
     */
    getDefaultIcon(name) {
        if (ITEM_ICONS[name]) {
            return ITEM_ICONS[name].emoji;
        }
        
        // 通用图标
        return '📦';
    }

    /**
     * HTML 转义
     * @param {string} text 
     * @returns {string}
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * 关闭背包
     */
    close() {
        // 如果是通过 window.open 打开的，关闭窗口
        if (window.opener) {
            window.close();
        } else {
            // 通知父页面（如果有）
            if (window.parent && window.parent !== window) {
                window.parent.postMessage({ type: 'backpack_closed' }, '*');
            }
        }
    }

    /**
     * 设置背包数据（供外部调用）
     * @param {object} data 背包数据 {items: [...]}
     */
    setData(data) {
        if (data && data.items) {
            this.items = data.items;
            this.render();
        }
    }
}

// 初始化
let backpackController;

document.addEventListener('DOMContentLoaded', () => {
    backpackController = new BackpackController();
    
    // 注册全局函数供外部调用
    window.setBackpackData = function(data) {
        if (backpackController) {
            backpackController.setData(data);
        }
    };

    // 监听来自父页面的消息
    window.addEventListener('message', (event) => {
        if (event.data && event.data.type === 'backpack_data') {
            if (backpackController) {
                backpackController.setData(event.data.data);
            }
        }
    });

    // 窗口事件隐藏 tooltip
    window.addEventListener('scroll', () => backpackController?.hideTooltip(), true);
    window.addEventListener('resize', () => backpackController?.hideTooltip());
});

// Tooltip 相关方法
BackpackController.prototype.showTooltip = function(item, slotEl) {
    const content = this.buildTooltipHtml(item);
    if (!this.tooltipEl) {
        this.tooltipEl = document.createElement('div');
        this.tooltipEl.className = 'item-tooltip';
        document.body.appendChild(this.tooltipEl);
    }
    this.tooltipEl.innerHTML = content;
    this.positionTooltip(slotEl);
    this.tooltipEl.style.display = 'block';

    // 绑定外部点击隐藏
    if (!this.boundOutsideHandler) {
        this.boundOutsideHandler = (e) => {
            if (!this.tooltipEl) return;
            if (e.target === slotEl || slotEl.contains(e.target)) return;
            if (e.target === this.tooltipEl || this.tooltipEl.contains(e.target)) return;
            this.hideTooltip();
        };
        document.addEventListener('pointerdown', this.boundOutsideHandler, true);
        document.addEventListener('keydown', (ev) => {
            if (ev.key === 'Escape') this.hideTooltip();
        }, { once: true });
    }
};

BackpackController.prototype.hideTooltip = function() {
    if (this.tooltipEl) {
        this.tooltipEl.style.display = 'none';
    }
    if (this.boundOutsideHandler) {
        document.removeEventListener('pointerdown', this.boundOutsideHandler, true);
        this.boundOutsideHandler = null;
    }
};

BackpackController.prototype.positionTooltip = function(slotEl) {
    if (!this.tooltipEl) return;
    const rect = slotEl.getBoundingClientRect();
    const margin = 8;
    let left = rect.left + margin;
    let top = rect.top - this.tooltipEl.offsetHeight - 12; // 上方

    // 如果上方放不下，则放在下方
    if (top < 0) {
        top = rect.bottom + margin;
        // 箭头朝上时不显示尾巴（简化处理）
        this.tooltipEl.style.transformOrigin = 'top left';
    } else {
        this.tooltipEl.style.transformOrigin = 'bottom left';
    }

    // 右侧边界校正
    const maxLeft = window.innerWidth - this.tooltipEl.offsetWidth - margin;
    if (left > maxLeft) left = maxLeft;
    if (left < margin) left = margin;

    this.tooltipEl.style.left = left + 'px';
    this.tooltipEl.style.top = top + 'px';
};

BackpackController.prototype.buildTooltipHtml = function(item) {
    const name = this.escapeHtml(item.name || '未知物品');
    const count = typeof item.count === 'number' ? item.count : 0;
    const rarity = this.escapeHtml(item.rarity || '白色');
    const descRaw = item.desc || item.description || '';
    const desc = this.escapeHtml(descRaw || '');

    // 数值限制
    const clamp = (v, min, max) => {
        v = typeof v === 'number' ? v : 0;
        if (v < min) v = min;
        if (v > max) v = max;
        return v;
    };

    const itemLevel = clamp(item.itemLevel, 1, 1000);
    const armor = clamp(item.armor, 0, 1000);
    const strength = clamp(item.strength, 0, 1000);
    const agility = clamp(item.agility, 0, 1000);
    const intelligence = clamp(item.intelligence, 0, 1000);
    const bindType = this.escapeHtml(item.bindType || '拾取后绑定,自由装备');
    const equipSlots = (item.equipSlots && item.equipSlots.length)
        ? item.equipSlots
        : ['头部','胸部','腿部'];

    const iconHtml = this.getItemIcon(item);

    const headHtml = `
        <div class="item-tooltip__head">
            <div class="item-tooltip__icon">${iconHtml}</div>
            <div class="item-tooltip__title">
                <div class="item-tooltip__name">${name}</div>
                <div class="item-tooltip__meta">稀有度：${rarity}　数量：${count}</div>
            </div>
        </div>
    `;

    const listHtml = `
        <div class="item-tooltip__list">
            <div class="item-tooltip__row">
                <div class="item-tooltip__label">属性:</div>
                <div class="item-tooltip__value">${bindType}</div>
            </div>
            <div class="item-tooltip__row">
                <div class="item-tooltip__label">介绍:</div>
                <div class="item-tooltip__value">${this.escapeHtml(equipSlots.join('，'))}</div>
            </div>
            <div class="item-tooltip__row">
                <div class="item-tooltip__label">物品等级:</div>
                <div class="item-tooltip__value">${itemLevel}</div>
            </div>
            <div class="item-tooltip__row">
                <div class="item-tooltip__label">+护甲:</div>
                <div class="item-tooltip__value">${armor}</div>
            </div>
            <div class="item-tooltip__row">
                <div class="item-tooltip__label">+力量:</div>
                <div class="item-tooltip__value">${strength}</div>
            </div>
            <div class="item-tooltip__row">
                <div class="item-tooltip__label">+敏捷:</div>
                <div class="item-tooltip__value">${agility}</div>
            </div>
            <div class="item-tooltip__row">
                <div class="item-tooltip__label">+智力:</div>
                <div class="item-tooltip__value">${intelligence}</div>
            </div>
        </div>
    `;

    const descHtml = desc ? `<div class="item-tooltip__desc">${desc}</div>` : '';

    return headHtml + descHtml + listHtml;
};

